package users.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;

import common.pojo.InfoEnum;
import common.service.BaseService;
import common.servlet.BaseServlet;
import common.util.ConstatFinalUtil;
import common.util.EncryptUtil;
import common.util.PageInfoUtil;
import users.dao.IAAdminsDao;
import users.dao.IARoleDao;
import users.dao.impl.AAdminsDaoImpl;
import users.dao.impl.ARoleDaoImpl;
import users.pojo.AAdmins;
import users.pojo.ARole;
import users.service.IUsersDbService;

/***
 * 用户模块Service
 * @author lby
 *
 */
public class UsersDbServiceImpl extends BaseService implements IUsersDbService
{
	private IARoleDao roleDao = new ARoleDaoImpl();
	private IAAdminsDao adminsDao = new AAdminsDaoImpl();
	private EncryptUtil encryptUtil = new EncryptUtil();
	

	@Override
	public JSONObject saveOneRoleService(ARole role)
	{
		JSONObject resultJson = new JSONObject();
		role.setCreateTime(new Date());
		role.setUpdateTime(new Date());
		/* 调用dao保存数据库 */
		int res = this.roleDao.saveOne(role);
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_ID.getInfo(), role.getId());
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public JSONObject updateOneRoleService(ARole role)
	{
		JSONObject resultJson = new JSONObject();
		role.setUpdateTime(new Date());
		/* 调用dao保存数据库 */
		int res = this.roleDao.updateOne(role);
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_ID.getInfo(), role.getId());
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public JSONObject deleteOneRoleService(Map<String, Object> condMap)
	{
		JSONObject resultJson = new JSONObject();
		/* 调用dao保存数据库 */
		int res = this.roleDao.deleteOne(condMap);
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public ARole findOneRoleService(Map<String, Object> condMap)
	{
		ARole role = this.roleDao.findOne(condMap);
		if("true".equalsIgnoreCase(condMap.get("extend")+""))
		{
			/*extend等于true表示查询扩展信息*/
			if(role != null)
			{
				/*请查询菜单*/
				/*请查询管理员*/
				Map<String,Object>extMap = new HashMap<String,Object>();
				extMap.put("roleId",role.getId());
				/*返回值是一个集合*/
				List<AAdmins>adminsList = this.findCondListAdminsService(null, extMap);
				role.setAdminsList(adminsList);
			}
		}
		return role;
	}

	@Override
	public List<ARole> findCondListRoleService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		 List<ARole>list = this.roleDao.findCondList(pageInfoUtil, condMap);
		  Map<String,Object> extMap = new HashMap<String,Object>();
		  if("true".equalsIgnoreCase(condMap.get("extend")+""))
		  {
			  for(ARole one :list)
			  {
				  /*请查询菜单*/
				  /*请查询管理员*/
				  extMap.put("id", one.getId());
				  /*返回值是一个集合*/
				  List<AAdmins> adminsList= this.findCondListAdminsService(null, extMap);
				  one.setAdminsList(adminsList);
			  }
		  }
		return list;
	}

	@Override
	public JSONObject saveOneAdminsService(AAdmins admins)
	{
		JSONObject resultJson = new JSONObject();
		/*邮箱不重复*/
		Map<String,Object>condMap = new HashMap<String,Object>();
		//清除一下里面的内容
		condMap.clear();
		condMap.put("email", admins.getEmail());
		 AAdmins adminsDb= this.findOneAdminsService(condMap);
		 if(adminsDb !=null)
		 {
			 /*说明查询到了*/
			 //cond:0
			 resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_EMAIL_EXISTS.getCode());
			 //info:邮箱已经存在，请更换一个
			 resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_EMAIL_EXISTS.getCode())));
		 }
		/*对密码加密*/
		admins.setPassword(this.encryptUtil.encodeStr(admins.getPassword()));
		admins.setCreateTime(new Date());
		admins.setUpdateTime(new Date());
		admins.setLastloginTime(new Date());
		/* 调用dao保存数据库 */
		int res = this.adminsDao.saveOne(admins);
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_ID.getInfo(), admins.getId());
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public JSONObject updateOneAdminsService(AAdmins admins)
	{
		JSONObject resultJson = new JSONObject();
		/*邮箱不重复*/
		Map<String,Object>condMap = new HashMap<String,Object>();
		//清除一下里面的内容
		condMap.clear();
		condMap.put("email", admins.getEmail());
		 AAdmins adminsDb= this.findOneAdminsService(condMap);
		 if(adminsDb !=null)
		 {
			 /*说明查询到了*/
			 //cond:0
			 resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_EMAIL_EXISTS.getCode());
			 //info:邮箱已经存在，请更换一个
			 resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_EMAIL_EXISTS.getCode())));
		 }
		admins.setUpdateTime(new Date());
		/* 调用dao保存数据库 */
		int res = this.adminsDao.updateOne(admins);
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_ID.getInfo(), admins.getId());
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public JSONObject deleteOneAdminsService(Map<String, Object> condMap)
	{
		JSONObject resultJson = new JSONObject();
		/* 调用dao保存数据库 */
		int res = this.adminsDao.deleteOne(condMap);
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public AAdmins findOneAdminsService(Map<String, Object> condMap)
	{
		AAdmins one =  this.adminsDao.findOne(condMap);
		if("true".equalsIgnoreCase(condMap.get("extend") + ""))
		{
			if(one != null)
			{
				/* extendMap */
				Map<String,Object> extMap = new HashMap<String, Object>();
				/* 为角色赋值
				 * 拿着管理员的roleId去角色表里面查询
				 * ~调用Service中查询角色的方法
				 * ~调用dao中查询角色的方法
				 * 
				 * 我们的关联信息只查询一层;想查询多层的时候需要在extMap中增加extend=true
				 *  */
				//this.roleDao.findOne(condMap);
				extMap.put("id", one.getRoleId());
				ARole role = this.findOneRoleService(extMap);
				one.setRole(role);
			}
		}
		return one ; 
	}

	@Override
	public List<AAdmins> findCondListAdminsService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		List<AAdmins> list = this.adminsDao.findCondList(pageInfoUtil, condMap);
		if("true".equalsIgnoreCase(condMap.get("extend")+""))
		{
			Map<String,Object>extMap = new HashMap<String,Object>();
			for(AAdmins one : list)
			{
				extMap.put("id",one.getRoleId());
				ARole role = this.findOneRoleService(extMap);
				one.setRole(role);
			}
		}
		return list;
	}

	@Override
	public JSONObject updateOneAdminsService(AAdmins admins, Map<String, Object> fileMap)
	{
		/* 先更新管理员信息 */
		JSONObject resultJSON = this.updateOneAdminsService(admins);
		if(resultJSON.getInteger("code") == InfoEnum.INFO_SUCCESS.getCode()&& !fileMap.isEmpty())
		{
			String souPath = admins.getPhotoPath() ; 
			
			/* 文件上传 */
			InputStream is = (InputStream) fileMap.get("is");
			String fileName = (String) fileMap.get("fileName");
			
			/* 拼装路径,完成上传
			 * 真实路径
			 * 网络路径
			 * 相对路径
			 *  */
			String truePath = ConstatFinalUtil.SYSTEM_JSON.getString("file.truePath") ; 
			String relaPath = ConstatFinalUtil.SYSTEM_JSON.getString("rela.path");
			relaPath += "/admins/" + this.dateUtil.dateToStr(new Date()) + "/" ;
			relaPath += UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
			
			/* 拼装我们的真实文件对象 */
			File trueFile = new File(truePath + relaPath);
			if(!trueFile.getParentFile().exists())
			{
				trueFile.getParentFile().mkdirs() ; 
			}
			try
			{
				FileOutputStream fos = new FileOutputStream(trueFile);
				/* 拷贝流 */
				if(this.ioUtil.copyFile(is, fos)) 
				
				{
					/* 拷贝成功,赶紧把相对路径存储到数据库中 */
					admins.setPhotoPath(relaPath);
					/* 就是为了更新路径 */
					this.updateOneAdminsService(admins);
					/* 删除老照片 */
					File souFile = new File(truePath + souPath); 
					if(!souFile.delete())
					{
						System.out.println("==删除文件失败了=;" + trueFile.getAbsolutePath());
					}
				}else
				{
					System.out.println("==上传文件失败了=;" + trueFile.getAbsolutePath());
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return resultJSON;
	}
}
